
// 检查值是否为错误值
let checkValue = function (value) {
  if (parseInt(value) == 0) {
    return true;
  }
  return ((value == "" || value == false || value == null || value == undefined || value == "undefined") ? false : true);
}

// 获取浏览器的设备信息
var getPlatform = function () {
  var u = navigator.userAgent;
  if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    return "ios"
  }
  else if (u.match(/Windows/)) {
    return "Windows"
  }
  else if (u.match(/Android/)) {
    return "Android"
  }
  else {
    return "未知"
  }
}

// 获取浏览器的search值
function getHttpsParams () {
  const paramsString = window.location.search.substring(1);
  const params = new URLSearchParams(paramsString);
  return params
}

function checkIsWeixin (app_id, unionid) {
  // 判断是否在微信中打开网页
  var ua = navigator.userAgent.toLowerCase()
  // 在微信中打开
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
      if (!checkValue(unionid)) {
        const params = getHttpsParams()
        const app_source = checkValue(params.get('s')) ? params.get('s') : "none"
        const platform = getPlatform()
        window.location.href = "https://ke.juzizhi.cn/api/yaoqingma?app_id=" + app_id + "&app_source=" + app_source + "&platform=" + platform;
      }
  }
  // 不是在微信浏览器中打开
  else {
    // 重新跳转 提示用户使用微信浏览器打开
    // window.location.href = "https://ke.juzizhi.cn/api/yaoqingma?app_id=" + app_id;
  }
}

Number.prototype.toPercent = function(){
    return (Math.round(this * 10000)/100).toFixed(2) + '%';
}

Number.prototype.toFloat2 = function(){
    return (Math.round(this * 10000)/100).toFixed(2);
}

Number.prototype.toInt = function(){
    return Math.ceil((Math.round(this * 10000)/100).toFixed(2) / 100);
}

String.prototype.firstUpperCase = function(){
    return this.replace(/\b(\w)(\w*)/g, function($0, $1, $2) {
        return $1.toUpperCase() + $2.toLowerCase();
    });
}

let url = "https://ke.juzizhi.cn/common/yaoqingma";
let common_post = function (path, params={}, callback) {
  params.token = $.cookie('token');
  $.post(url + path, params, function (res) {
    callback(res);
  })
}

let weixinShare = function (title, link, desc, imgurl) {
  common_post('/signature',{account: "xiaotikuya"},function (signature) {
    // alert(JSON.parse(signature));
    wx.config({
        debug: false,
        app_id: signature.app_id,
        timestamp: signature.timestamp,
        nonceStr: signature.noncestr,
        signature: signature.signature,
        jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage', 'hideMenuItems']
    });

    wx.ready(function () {
      wx.hideMenuItems({
      menuList: [
        "menuItem:share:qq",
        "menuItem:share:weiboApp",
        "menuItem:share:facebook",
        "menuItem:share:QZone",
        "menuItem:copyUrl",
        "menuItem:openWithQQBrowser",
        "menuItem:openWithSafari",
        "menuItem:share:email"
        ] // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
      });

      wx.onMenuShareTimeline({
        title: desc, // 分享标题
        link: link, // 分享链接
        imgUrl: imgurl, // 分享图标
        success: function () {
            // 用户确认分享后执行的回调函数
        },
        cancel: function () {
            // 用户取消分享后执行的回调函数
        }
      });
      wx.onMenuShareAppMessage({
          title: title, // 分享标题
          desc: desc, // 分享描述
          link: link, // 分享链接
          imgUrl: imgurl, // 分享图标
          type: 'link', // 分享类型,music、video或link，不填默认为link
          dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
          success: function () {
              // 用户确认分享后执行的回调函数
          },
          cancel: function () {
              // 用户取消分享后执行的回调函数
          }
      });
    });
    wx.error(function (res) {

    });
  });
}

let get_access_token = function (app_id, callback) {
  let access_token = $.cookie("access_token_" + app_id);
  let app = JSON.parse(window.localStorage.getItem("app_" + app_id));

  window.application_id = app_id;

  if (!checkValue(access_token) || !checkValue(app)) {
    common_post("/get_app_access_token", {app_id}, function (res) {
      if (parseInt(res.code, 10) == 200) {
        access_token = res.access_token;
        var date = new Date();
        date.setTime(date.getTime() + (10 * 60 * 1000));
        $.cookie("access_token_" + app_id, access_token, {expires: date, path: "/"});
        window.localStorage.setItem("app_" + app_id, JSON.stringify(res.app));
        callback(access_token, res.app)
      }
      else {
        callback(null, null);
      }
    })
  }

  callback(access_token, app)
}


export default {
  checkValue,
  common_post,
  weixinShare,
  checkIsWeixin,

  /** 一切支付请求皆原于此处 */
  pay_post: function (path, params, callback) {

    // wx.showLoading({
    //   mask: !0,
    //   title: "支付发起中.."
    // })

    // params.adminid = adminid
    // params.appid = appid
    // params.app_id = app_id
    // params.openid = wx.getStorageSync("user_openid")
    // params.unionid = wx.getStorageSync("user_unionid")

    params.app_source = ""
    params.friend_unionid = ""
    params.platform = getPlatform()

    $.post("https://ke.juzizhi.cn/common/pay" + path, params, function (res) {
      callback(res);
    })
  }
}
